<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2018\1\15 0015
 * Time: 10:42
 */
namespace common\models;

use yii\db\ActiveRecord;

class ProjectLock extends ActiveRecord{

    //上锁
    public static function Lock($tableModel,$user_id,$project_id,$where_ziduan){
        $projectTableModel = $tableModel::find()->where(['=',$where_ziduan,$project_id])->one();
        if (empty($projectTableModel)){
            $projectTableModel = new $tableModel;
            $projectTableModel->$where_ziduan = $project_id;
        }
        $projectTableModel->lock_user = $user_id;
        $projectTableModel->lock_timestamp = time();
        $projectTableState = $projectTableModel->save(false);
        if ($projectTableState){
            return Responses::response200('',1,'上锁成功');
        }
        return Responses::response400('加锁失败，请重试');
    }

    //解锁
    public static function Unlock($tableModel,$project_id,$where_ziduan){
        $projectTableModel = $tableModel::find()->where(['=',$where_ziduan,$project_id])->one();
        $projectTableModel->lock_user = null;
        $projectTableModel->lock_timestamp = time();
        $projectTableState = $projectTableModel->save(false);
        if ($projectTableState){
            return Responses::response200('',1,'解锁成功');
        }
        return Responses::response400('解锁失败，请重试');
    }

    //查看锁状态
    public static function SelectLock($tableModel,$project_id,$where_ziduan){
        $projectTableModel =  $tableModel::find()->where(['=',$where_ziduan,$project_id])->one();
        $projectTableData = $projectTableModel['lock_user'];
        $userId = \Yii::$app->user->getId();
        $user_name = User::find()->where(['=','id',$projectTableData])->one()['realname'];
        if (empty($projectTableData) || $projectTableData==$userId){
            return Responses::response200($projectTableData,1,'无上锁');
        }else{
            return Responses::response400($user_name."正在编辑");
        }
    }
}